﻿using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraReports.UI;

using prjKQXS_DLL;
using prjKQXS_DLL.Truyen_thong;
using prjKQXS_Report.Truyen_thong;

namespace prjKQXS_UI.Truyen_thong
{
    public partial class frmNhapVeHuy_DV : DevExpress.XtraEditors.XtraForm
    {
        clsHuyVe cls = new clsHuyVe();
        public int GiaVe = 0;
        public string KyHieu = "";

        #region Form =============================================================================
        public frmNhapVeHuy_DV()
        {
            InitializeComponent();

            cls.OnAction += new clsHuyVe.OnActionHandler(cls_OnAction);
            cls.OnError += new clsHuyVe.OnErrorHandler(cls_OnError);
        }

        private void frmNhapVeHuy_DV_Shown(object sender, EventArgs e)
        {
            deNgay.DateTime = BienTc.denngay;
            gvDonVi1.OptionsBehavior.Editable = deNgay.DateTime.Date == DateTime.Now.Date; 
            Taosoluongvedv(BienTc.denngay);
            gcDonVi1.DataSource = Loadvesohuydv1(deNgay.DateTime);
            updategiatridv1(BienTc.GiaVe, BienTc.KyHieuVe, BienTc.denngay);
            gcDonVi2.DataSource = Loadvesohuydvct(deNgay.DateTime);            
        }
        #endregion Form ==========================================================================


        #region Control ==========================================================================
        //Thủ tục này và sbtnInTongHop bên cán bộ là giống nhau
        private void sbtnIn_Click(object sender, EventArgs e)
        {
            rptTongHopTT_DV rpt = new rptTongHopTT_DV();
            rpt.dtSource = cls.rptTongHop_CB('%', deNgay.DateTime, deNgay.DateTime, ref rpt.TyLe, ref rpt.VietBangSo);
            rpt.xrtcGiaVe.Text = GiaVe.ToString("#,#đ");
            rpt.xrtcKyHieu.Text = KyHieu;
            rpt.pNgay.Value = deNgay.DateTime.Date;
            rpt.ShowRibbonPreviewDialog();
        }

        private void btnTim_Click(object sender, EventArgs e)
        {
            Anf4(); 
        }       

        private void btndong_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion Control =======================================================================


        #region Sub and Func =====================================================================
        #region cls event --------------------------------------------
        private void cls_OnAction(SqlException e)
        {
            cls_OnError(e);
        }

        private void cls_OnError(Exception e)
        {
            XtraMessageBox.Show("Một lỗi chưa được xử lý đã xảy ra. Chi tiết lỗi: \n" + e.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }
        #endregion cls event -----------------------------------------

        private void Taosoluongvedv(DateTime Ngay)
        {
            SqlConnection conn = new SqlConnection(BienTc.connString);
            SqlCommand cmd = null;
            string sql = @"Select DV.Ma_DT
                            from DMDONVI DV
                            where DV.isPublic = 1
                                and DV.Ma_DT <> '9' 
                                and DV.Ma_DT <> 'K' 
                                and DV.Ma_DT <> 'O' 
                                and DV.Ma_DT <> 'V'
                                and DV.Ma_DT not in (
			                            Select VS.Ma_DMDonVi
                                        FROM  tblVESO_CT VS INNER JOIN DMDONVI ON DMDONVI.Ma_DT = VS.Ma_DMDonVi
			                            WHERE DMDONVI.isPublic = 1 and VS.isPublic = 1
                                            and VS.NgayMoThuong = @Ngay
		                            )
		                    ORDER BY DV.Ma_DT";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.SelectCommand.Parameters.AddWithValue("@Ngay", Ngay);
            DataTable dtDONVI = new DataTable();
            da.Fill(dtDONVI);

            foreach (DataRow dr in dtDONVI.Rows)
            {
                sql = @"INSERT INTO tblVESO_CT(Ma_DMDonVi, NgayMoThuong) VALUES(@Ma_DMDonVi, @NgayMoThuong)";
                cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Ma_DMDonVi", dr["Ma_DT"]);
                cmd.Parameters.AddWithValue("@NgayMoThuong", Ngay);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                cmd.ExecuteNonQuery();
            }
        }

        private DataTable Loadvesohuydv1(DateTime Ngay)
        {
            SqlConnection conn = new SqlConnection(BienTc.connString);
            DataTable dt = new DataTable();
            string sql = @"Select VS.ID
                            , DV.Ma_DT AS MaDV
                            , DV.Ten_DT AS TenDV
                            , SLVeNhan
                            , SLVeHuy
                            , ( CASE WHEN SLVeNhan is null and SLVeHuy is null THEN null
                                        ELSE (CASE WHEN SLVeNhan is null THEN 0 ELSE SLVeNhan END - CASE WHEN SLVeHuy is null THEN 0 ELSE SLVeHuy END)
                                END) AS SLVeBan
                        FROM tblVESO_CT VS INNER JOIN DMDonVi DV On DV.Ma_DT = VS.Ma_DMDonVi
                        Where DV.Ma_DT not in ('9', 'T', 'K', 'O') 
                            and NgayMoThuong = @Ngay 
                        order by DV.Ma_DT";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.SelectCommand.Parameters.AddWithValue("@Ngay", Ngay);
            da.Fill(dt);

            return dt;
        }

        private DataTable Loadvesohuydvct(DateTime Ngay)
        {
            SqlConnection conn = new SqlConnection(BienTc.connString);
            DataTable dt = new DataTable();
            string sql = @"Select Ma_DMDonVi as MaDV
                                , TenDV
                                , Sum(VS.SLVeNhan) as SLVeNhan
                                , Sum(VS.SLVeHuy) as SLVeHuy
                                , (Sum(VS.SLVeNhan) - Sum(VS.SLVeHuy)) as SLVeBan 
                            FROM  vVESO VS
                            Where VS.isPublic = 1
                                and NgayMoThuong = @Ngay  
                            group by Ma_DMDonVi
                                , TenDV 
                            order by Ma_DMDonVi";
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            da.SelectCommand.Parameters.AddWithValue("@Ngay", Ngay.Date);
            da.Fill(dt);

            return dt;
        }

        private int updategiatridv1(object GiaVe, object KyHieu, DateTime ngay)
        {
            SqlConnection conn = new SqlConnection(BienTc.connString);
            try
            {
                conn.Open();
                string sql = @"UPDATE tblVESO_CT SET Giave = @GiaVe, Kyhieu = @KyHieu 
                                FROM tblVESO_CT VS INNER JOIN DMDONVI DV ON DV.Ma_DT = VS.Ma_DMDonVi
                                where DV.isPublic = 1 and VS.isPublic = 1
	                                and NgayMoThuong = @Ngay
                                    and Ma_DMDonVi not in ('9', 'K', 'O', 'V')";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@GiaVe", GiaVe);
                cmd.Parameters.AddWithValue("@KyHieu", KyHieu);
                cmd.Parameters.AddWithValue("@Ngay", ngay.Date);
                return cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                clsCommon.MsgBox("Có lỗi xảy ra, vui lòng kiểm tra lại !\n" + ex.Message, 0);
                return 0;
            }
            finally
            {
                conn.Close();
            }
        }

        private void Anf2()
        {
            gvDonVi1.Focus();
            gvDonVi1.OptionsBehavior.Editable = true;
            gcolSLVeHuy1.OptionsColumn.AllowFocus = false;
            gcolSLVeHuy1.OptionsColumn.AllowEdit = false;
            gcolSLVeNhan1.OptionsColumn.AllowFocus = true;
            gcolSLVeNhan1.OptionsColumn.AllowEdit = true;
            gvDonVi1.FocusedRowHandle = 0;
            gvDonVi1.FocusedColumn = gvDonVi1.Columns["SLVeNhan"];
        }

        private void Anf3()
        {
            gvDonVi1.Focus();
            gvDonVi1.OptionsBehavior.Editable = true;
            gcolSLVeHuy1.OptionsColumn.AllowFocus = true;
            gcolSLVeHuy1.OptionsColumn.AllowEdit = true;
            gcolSLVeNhan1.OptionsColumn.AllowFocus = false;
            gcolSLVeNhan1.OptionsColumn.AllowEdit = false;
            gvDonVi1.FocusedRowHandle = 0;
            gvDonVi1.FocusedColumn = gvDonVi1.Columns["SLVeHuy"];
        }

        private void Anf4()
        {
            gvDonVi1.Focus();
            gvDonVi1.OptionsBehavior.Editable = true;
            gcolSLVeNhan1.OptionsColumn.AllowFocus = true;
            gcolSLVeNhan1.OptionsColumn.AllowEdit = true;
            gcolSLVeHuy1.OptionsColumn.AllowFocus = true;
            gcolSLVeHuy1.OptionsColumn.AllowEdit = true;
            gvDonVi1.FocusedRowHandle = 0;
            gvDonVi1.FocusedColumn = gvDonVi1.Columns["SLVeNhan"];
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F2)
            {
                Anf2();
            }
            if (keyData == Keys.F3)
            {
                Anf3();
            }
            if (keyData == Keys.F4)
            {
                Anf4();
            }
            else if (keyData == Keys.F7)
            {
                sbtnIn_Click(null, null);
            }
            else if (keyData == Keys.F8)
            {
                this.Close();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion Sub and Func ==================================================================


        #region gv ===============================================================================
        private void gvDonVi1_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            string a = e.Value.ToString();
            if (a.ToString().Length != 0)
            {
                foreach (char c in a)
                {
                    if (!char.IsDigit(c))
                    {
                        clsCommon.MsgBox("Bạn phải nhập giá trị là số ", 0);
                    }
                }
            }
        }

        private void gvDonVi1_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.ToUpper() == "SLVENHAN" || e.Column.FieldName.ToUpper() == "SLVEHUY")
            {
                int i = 0, i1 = 0;
                if (clsTruyenThong.DaNhapVesoRoi('T', deNgay.DateTime, gvDonVi1.GetFocusedDataRow()["MaDV"].ToString().Trim()))
                {
                    XtraMessageBox.Show("Không nhập được ở đây vì chi tiết đã nhập bên đại lý hoặc cán bộ rồi");
                }
                else
                {
                    clsCommon.updateRowValue("tblVESO_CT", e.Column.FieldName.ToUpper(), "Where ID = " + gvDonVi1.GetFocusedDataRow()["ID"].ToString(), e.Value);

                    object o = clsCommon.Parse(gvDonVi1.GetFocusedDataRow()["SLVeNhan"].ToString(), 0);
                    object o1 = clsCommon.Parse(gvDonVi1.GetFocusedDataRow()["SLVeHuy"].ToString(), 0);
                    
                    i = o.ToString().Trim() == "" ? 0 : (int)o;
                    if (e.Column.FieldName.ToUpper() == "SLVEHUY") i1 = o1.ToString().Trim() == "" ? 0 : (int)o1;

                    if (i < i1)
                        clsCommon.MsgBox("Số lượng vé hủy không thể lớn hơn số lượng vé nhận. Hãy sửa lại số lượng vé cho đúng với thực tế", 0);

                    isLoad = true;
                    gcDonVi1.DataSource = Loadvesohuydv1(deNgay.DateTime);
                    gcDonVi2.DataSource = Loadvesohuydvct(deNgay.DateTime);
                    isLoad = false;
                    gvDonVi1.FocusedRowHandle = focusRow;
                }

                if (i + i1 > 0) gvDonVi1.SetFocusedRowCellValue("SLVeBan", i - i1);
            }
        }

        private void gvcanbo_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
        {
            string a = e.Value.ToString();
            if (a.ToString().Length == 0)
            {
                e.Value = 0;
            }
        }
        
        private void gvcanbo_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gvcanbo_LostFocus(object sender, EventArgs e)
        {
            gcDonVi1.DataSource = Loadvesohuydv1(deNgay.DateTime);
        }
        private bool isLoad = false;
        private int focusRow = 0;
        private void gvcanbo_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (!isLoad)
            {
                focusRow = e.FocusedRowHandle;                
            }
        }
        
        private void gvDonvi_Click(object sender, EventArgs e)
        {
            gcDonVi2.DataSource = Loadvesohuydvct(deNgay.DateTime);            
        }

        private void gvDonvi_GotFocus(object sender, EventArgs e)
        {
            gcDonVi2.DataSource = Loadvesohuydvct(deNgay.DateTime);            
        }
        #endregion gv ============================================================================
    }
}